<?php
/*账户相关明细*/

namespace App\Controller\User;

use App\Controller\ApiController;
use Usap\Service\Lottery\d3process;
use Usap\Service\Service;
use Usap\Service\Account\wallet;
use Usap\Service\Event\Bonus\bonusEvent;
use Usap\Service\Event\Bonus\userBonusEvent;

class RecordController extends ApiController
{
    /*
     * 追号计划列表
    */
    public function getPlanList()
    {

        //时间(period)、彩种()、追号状态(全部，进行中，已完成)、商品状态(代付款，进行中，交易关闭，已完成)
        /*
         * 追号状态type:进行中-jxz 全部-all 已完成-ywc(导航栏中)
         * 高级搜索中：
         * 时间：period: -3_months,-1_weeks,-0_days
         * 彩种：lotteryType: all,DLT,PL3,QXC...
         * 商品状态：goodStatus:等待付款dfg,进行中jxz,已完成ywc,交易关闭close
         * 开奖状态：prizeStaus	：yes:已中奖，no:未中奖
         */
        $user_id = $this->context->userId;
// 		$login_url = '/account/login?from='.rawurlencode('/urecord/getPlanList');

        //区分是购买方案，保存方案
        $consignType = $this->partCloudConf['common']['consign_type'];
        $consignType = ucfirst($consignType);
        $consignTypeConf = array_keys(Service::instance()->loadConfig('lottery', 'plan', getConsignTypeConf));
        if (!in_array($consignType, $consignTypeConf)) $this->ajaxReturn(array('code' => '-2', 'code_str' => '不支持的购买方式'));

        //前端展示状态配置
        if ($consignType == 'Alone') {

            $run_status_cn_conf = array(
                'Not' => '等待付款', 'Stop' => '已完成', 'Pay' => '进行中', 'Run' => '进行中',
            );
        } elseif ($consignType == 'Save') {

            $run_status_cn_conf = array(
                'Not' => '未开始', 'Stop' => '已完成', 'Pay' => '进行中', 'Run' => '进行中',
            );

        }
        $paraStr = I('request.para');
        $param_list = $this->decrypt($paraStr);
        $type = $param_list['type'] ? $param_list['type'] : 'all';
        $period = empty($param_list['period']) ? '-3_months' : $param_list['period'];
        $page = $param_list['page'] + 0;
        $pageSize = $param_list['pageSize'] ? $param_list['pageSize'] + 0 : 10;
        $lotteryType = empty($param_list['lotteryType']) ? 'all' : $param_list['lotteryType'];
        $goodStatus = $param_list['goodStatus'];
        $prizeStaus = $param_list['prizeStaus'];

        if (empty($user_id)) {
            $data = array('code' => -1, 'code_str' => '请登录后查看');
            return $this->ajaxReturn($data);
        }
        if (!in_array($type, array('all', 'jxz', 'ywc'))) {
            $data = array('code' => -2, 'code_str' => '参数不合法');
            return $this->ajaxReturn($data);
        }
        $check_info = $this->checkPeriodParam($period);
        if ($check_info['code'] !== '0000') {
            $this->ajaxReturn($check_info);
        }

        $start_time = $check_info['start_time'];
        $end_time = $check_info['end_time'];

        $plan_service = Service::instance()->find('plan', 'plan');
        $plan_list = $plan_service->getPlanList($user_id, $lotteryType, $type, $page, $pageSize, $start_time, $end_time, $goodStatus, $prizeStaus, $consignType);

        //处理plan_list ,返回符合模板需求数据
        $return_list = array();

        if ($plan_list && is_array($plan_list['list'])) {

            foreach ($plan_list['list'] as $key => $val) {

                //根据代购,保存类型  区别前端展现方式
                /**
                 * 代购型
                 * 等待付款、进行中、已完成
                 * 保存型
                 * 未开始、进行中（奖金>0 显示累积中奖＊＊元）、已完成（奖金>0显示累积中奖、奖金＝0显示未中奖）
                 */

                if ($consignType == 'Alone') {

                    $run_status_cn = $run_status_cn_conf[$val['run_status']];
                } elseif ($consignType == 'Save') {
                    if ($val['run_status'] == 'Not') {

                        $run_status_cn = $run_status_cn_conf[$val['run_status']];
                    } elseif (in_array($val['run_status'], array('Pay', 'Run'))) {

                        $run_status_cn = $val['total_prize'] > 0 ? "累计中奖 {$val['total_prize']} 元" : $run_status_cn_conf[$val['run_status']];
                    } elseif ($val['run_status'] == 'Stop') {

                        $run_status_cn = $val['total_prize'] > 0 ? "累计中奖 {$val['total_prize']} 元" : '未中奖';
                    }
                }

                $return_list[$key] = array(
                    'plan_id' => $val['plan_id'],
                    'run_status' => $val['run_status'],
                    'get_ticket_self' => $val['get_ticket_self'],
                    'create_time' => date('y-m-d', strtotime($val['create_time'])),
                    'money' => $val['money'],
                    'lottery_type' => $val['lottery_type'],
                    'lottery_type_cn' => $val['lottery_type_cn'],
                    'actual_exec_count' => $val['actual_exec_count'],//实际追号执行期次
                    'expect_exec_count' => $val['expect_exec_count'],//期望执行期次
                    'run_status_cn' => $run_status_cn,//商品状态中文形式
                    'total_prize' => $val['total_prize'],//总的中奖金额
                );
            }
        }

        $info = array(
            'type' => $type, 'page' => $page, 'totalPage' => $plan_list['totalPage'], 'count' => $plan_list['count'], 'list' => $return_list, 'v' => I('request.v'),
        );
        $str = $this->encrypt($info);
        $data = array('code' => 0, 'code_str' => '成功', 'info' => $str);

        return $this->ajaxReturn($data);

    }

    /*
     * lotteryType   'all/DLT/PL3'
     * buyType    合买类型; all:全部、alone:代购、consign:合买、plan:追号
     * prizeStaus	开奖状态; all:全部、prize:已中奖、yes:已开奖、no:未开奖
     * goodsStatus	 商品状态;all:全部、on:进行中、deal:成交、fail:交易失败
     * type    yzj 已中奖   dcp待出票    dkj  待开奖     wzj   未中奖    dfk  代付款  全部 all  出票失败 cpsb
     * 投注列表 */
    public function getLaunchList()
    {
        $userId = $this->context->userId;
        $paraStr = I('request.para');
        $param_list = $this->decrypt($paraStr);
        //$login_url = '/account/login?from='.rawurlencode('/urecord/getlaunchlist');
        $period = empty($param_list['period']) ? '-3_months' : $param_list['period'];
        $type = empty($param_list['type']) ? 'all' : $param_list['type'];
        $lotteryType = empty($param_list['lotteryType']) ? 'all' : $param_list['lotteryType'];
        $buyType = empty($param_list['buyType']) ? 'all' : $param_list['buyType'];
        //$buyType = $this->partCloudConf['common']['consign_type'];
        $goodStatus = $param_list['goodStatus'] ? $param_list['goodStatus'] : 'all';//交易状态
        $page = $param_list['page'] + 0;
        $pageSize = $param_list['pageSize'] ? $param_list['pageSize'] + 0 : 10;
        $v = $param_list['v'];
        $check_info = $this->checkPeriodParam($period);
        if (empty($userId)) {
            $data = array('code' => -1001, 'code_str' => '请请登录后查看', 'info' => '');
            return $this->ajaxReturn($data);
        }
        if (!in_array($type, array('all', 'yzj', 'dkj', 'wzj', 'dfk', 'dcp', 'cpsb'))) {
            $data = array('code' => -1002, 'code_str' => '参数不合法', 'info' => '');
            return $this->ajaxReturn($data);
        }
        if (!in_array($buyType, array('all', 'alone', 'consign', 'plan', 'save'))) {
            $data = array('code' => -1003, 'code_str' => '参数不合法', 'info' => '');
            return $this->ajaxReturn($data);
        }
        $startTime = $check_info['start_time'];
        $endTime = $check_info['end_time'];

        $userService = Service::instance()->find('account', 'user');
        $recordService = Service::instance()->find('account', 'record');
        $scheduleService = Service::instance()->find('schedule', 'num');
        $lotteryInfo = $recordService->getLaunchList($userId, $page, $pageSize, $startTime, $endTime, $type, $lotteryType, $buyType, $goodStatus);
        $lotteryList = array();
        $totalPage = 0;
        if ($lotteryInfo['list'] && is_array($lotteryInfo['list'])) {
            $totalPage = ceil($lotteryInfo['count'] / $pageSize);

            foreach ($lotteryInfo['list'] as $key => $val) {
                $lotteryList[$key]['lotteryId'] = $val['lottery_id'];
                $lotteryList[$key]['lotteryType'] = $val['lottery_type'];
                $lotteryList[$key]['lotteryNo'] = $val['lottery_no'];
                //  $nowLotteryNo = $scheduleService->getCurrentLotteryNo($val['lottery_type']);
                if ($val['build_from_target'] == 'common') {
                    $lotteryList[$key]['recordType'] = '直投';
                } elseif ($val['build_from_target'] == 'plan') {
                    $lotteryList[$key]['recordType'] = '追号';
                }
//                if ($val['consign_type'] == 'together') {
//                    $lotteryList[$key]['recordType'] = '合买';
//                }

                $lotteryList[$key]['lotteryTypeCn'] = $val['lottery_type_cn'];
                if (in_array($val['build_from_target_id'], array('2', '3')) && $val['lottery_type'] == 'FTFH') {
                    $lotteryList[$key]['lotteryType'] = "JZ2X1";
                    $lotteryList[$key]['lotteryTypeCn'] = "竞足-2选1";
                }
                $lotteryList[$key]['money'] = $val['money'];
                $lotteryList[$key]['time'] = date('y/m/d', strtotime($val['create_time']));
                $lotteryList[$key]['status'] = '';

                if ($this->partCloudConf['common']['consign_type'] == 'save') {

                    // 保存
                    if ($val['prize_status'] == 'Not') {
                        $lotteryList[$key]['status'] = '待开奖';
                    }
                    if ($val['raw_prize'] > 0) {
                        if ($val['raw_prize'] >= 10000) {
                            $lotteryList[$key]['status'] = '大奖 ' . $val['raw_prize'];
                        } else {
                            $lotteryList[$key]['status'] = '中奖 ' . $val['raw_prize'];
                        }
                    } elseif ($val['raw_prize'] == 0) {
                        $lotteryList[$key]['status'] = '未中奖';
                    }

                } else {
                    //on 合买中 ，deal 付款成功，not未付款
                    if ($val['goods_status'] == 'not') {
                        // 						if($nowLotteryNo == $val['lottery_no']){
                        // 							$lotteryList[$key]['status'] = '等待付款';
                        // 						}else{
                        // 							$lotteryList[$key]['status'] = '交易关闭';
                        // 						}
                        if (time() < strtotime($val['sell_end_time'])) {
                            $lotteryList[$key]['status'] = '等待付款';
                        } else {
                            $lotteryList[$key]['status'] = '交易关闭';
                        }
                    } elseif (in_array($val['goods_status'], ['on', 'deal'])) {//付款完成(票全成功、全失败、部分失败)

                        if (in_array($val['print_status'], ['not', 'on', 'split', 'printing'])) {
                            $lotteryList[$key]['status'] = '等待出票';
                        } elseif ($val['print_status'] == 'yes') {

                            $lotteryList[$key]['status'] = '出票成功';

                            if ($val['real_money'] != $val['money']) {
                                $lotteryList[$key]['status'] = '部分成功';
                            }

                            if ($val['prize_status'] == 'Not') {
                                $lotteryList[$key]['status'] = '待开奖';
                            }
                            if ($val['net_prize'] > 0) {
                                if ($val['real_prize'] > 0) {
                                    if ($val['raw_prize'] > 10000) {
                                        if ($val['raw_prize'] == $val['net_prize']) {
                                            $lotteryList[$key]['status'] = '中奖 ' . $val['real_prize'];
                                        } else {
                                            $lotteryList[$key]['status'] = '大奖 ' . $val['real_prize'];
                                        }
                                    } else {
                                        $lotteryList[$key]['status'] = '中奖 ' . $val['real_prize'];
                                    }
                                } else {
                                    if ($val['raw_prize'] > 10000) {
                                        $lotteryList[$key]['status'] = '<span class="gray">' . '大奖 ' . $val['net_prize'] . '</span>';
                                    } else {
                                        $lotteryList[$key]['status'] = '<span class="gray">' . '中奖 ' . $val['net_prize'] . '</span>';
                                    }
                                }
                            } elseif ($val['raw_prize'] == 0) {
                                $lotteryList[$key]['status'] = '未中奖';
                            }
                            //if($val['raw_prize'] > 0){

                            //if($val['net_prize'] != $val['raw_prize']){//大奖标记
                            ///	$lotteryList[$key]['status'] = '大奖 '.$val['real_prize'];
                            //}else{
                            //	$lotteryList[$key]['status'] = '中奖 '.$val['real_prize'];
                            //}
                            //}elseif($val['raw_prize'] == 0){
                            //	$lotteryList[$key]['status'] = '未中奖';
                            //}
                        } else {
                            $lotteryList[$key]['status'] = '出票失败';
                        }
                    } elseif ($val['goods_status'] == 'cancel') {
                        $lotteryList[$key]['status'] = '交易关闭';
                    } elseif ($val['goods_status'] == 'fail') {
                        $lotteryList[$key]['status'] = '出票失败';
                    }
                }

            }
        }
        if (empty($lotteryList)) {
            $data = array('code' => '-1004', 'code_str' => '已显示全部');
        }

        $info = array();
        $info['type'] = $type;
        $info['page'] = $page;
        $info['totalPage'] = $totalPage;
        $info['v'] = $v;
        $info['count'] = $lotteryInfo['count'];
        $info['list'] = $lotteryList;
        $str = $this->encrypt($info);
        $data = array('code' => '0000', 'code_str' => 'suc', 'info' => $str);
//        dprint($data);
        return $this->ajaxReturn($data);
    }

    /*
     * 订单搜索
     *  */
    public function search()
    {
        $this->display('Record/search');
    }

    /*
     * 订单搜索列表
     *  */
    public function searchResult()
    {
        $period = $this->getArg('period');
        $lotteryType = $this->getArg('lotteryType');
        $buyType = $this->getArg('buyType');
        $checkTime = $this->getArg('checkTime');
        $type = $this->getArg('type');
        $v = $this->getArg('v');
        $this->assign('period', $period);
        $this->assign('lotteryType', $lotteryType);
        $this->assign('type', $type);
        $this->assign('buyType', $buyType);
        $this->assign('v', $v);
        $this->display('Record/searchresult');
    }

    /*积分明细*/
    public function score()
    {

        $user_id = $this->context->userId;
        // echo $user_id;die;
        //$login_url = '/account/login?from='.rawurlencode('/urecord/score');

        if (empty($user_id)) {

            $data_list = array('code' => '-1001', 'msg' => '当前记录在登录后才可查看');
            return $this->ajaxReturn($data_list);
        }

        $paraStr = I('request.para');
        $param_list = $this->decrypt($paraStr);
        $period = empty($param_list['period']) ? '-3_months' : $param_list['period'];//时间标志:默认最近三个月 -3_months
        $income_type = $param_list['income_type'];//收支类型
        $summary_type = $param_list['summary_type'];//类型
        $page = $param_list['page'] >= 0 ? $param_list['page'] : '-1';
        $page_size = empty($param_list['page_size']) ? 10 : $param_list['page_size'];

        //校验时间标志
        $check_info = $this->checkPeriodParam($period);
        if ($check_info['code'] != '0000') {
            return $this->ajaxReturn($check_info);
        }

        $start_time = $check_info['start_time'];
        $end_time = $check_info['end_time'];
        $score_list = Service::instance()->find('account', 'record')->getAccountList($user_id, $start_time, $end_time, 'score', $income_type, $summary_type, $page, $page_size);;
        $remain_info = Service::instance()->find('account', 'wallet')->getAvailableRemain($user_id, 'score');
        $score_list['code'] = '0000';
        $score_list['v'] = $param_list['v'];//防重复点击
        $score_list['income_type'] = $income_type;
        $score_list['page'] = $page;
        $score_list['remain'] = $remain_info['Score'];//可用余额
        if ($score_list['list']) {
            $filter_list = array();//定义初始化过滤列表
            foreach ($score_list['list'] as $key => $value) {

                $create_timestamp = strtotime($value['create_time']);
                $time_period = substr(date('Y', $create_timestamp), -2) . '-' . date('m-d', $create_timestamp);
                $coin_type = $value['coin_in'] > 0 ? 'in' : 'out';
                $symbol_type = $coin_type == 'in' ? '+' : '-';
                $consign_type = '';
                if (!empty($value['target_id'])) {
                    $lotteryServer = Service::instance()->find('lottery', 'lottery');
                    $projectInfo = $lotteryServer->getLotteryInfo($value['target_id']);
                    $consign_type = $projectInfo['consignType'];
                }
                $filter_list[] = array(
                    'item_cn' => $value['summary_cn'],
                    'create_date' => $time_period,
                    'create_time' => date('H:i:s', $create_timestamp),
                    'amount' => $symbol_type . $value["coin_{$coin_type}"],
                    'target_type' => empty($value['target_type']) ? '' : $value['target_type'],
                    'target_id' => empty($value['target_id']) ? '' : $value['target_id'],
                    'consign_type' => $consign_type,
                );
            }
            unset($score_list['list'], $score_list['sum_coinin'], $score_list['sum_coinout']);
            $score_list['list'] = $filter_list;
        } else {
            $score_list['list'] = array();
        }
        $str = $this->encrypt($score_list);
        if (empty($score_list)) {
            $this->ajaxReturn(array("code" => '-1002', 'cod_str' => "积分信息获取失败", 'info' => ''));
        } else {
            $this->ajaxReturn(array("code" => '0000', 'cod_str' => "积分信息获取成功", 'info' => $str));
        }

    }

    /*现金明细*/
    public function cash()
    {
        $user_id = $this->context->userId;
        if (empty($user_id)) {
            $this->ajaxReturn(array('code' => '-1001', 'code_str' => "请先登录"));
        }
        $paraStr = I('request.para');
        $param_list = $this->decrypt($paraStr);
        $period = empty($param_list['period']) ? '-3_months' : $param_list['period'];//时间标志:默认最近三个月 -3_months
        $income_type = $param_list['income_type'];//收支类型
        $summary_type = $param_list['summary_type'];//类型
        $page = ($param_list['page'] >= 0 && isset($param_list['page'])) ? $param_list['page'] : '-1';
        $page_size = empty($param_list['page_size']) ? 10 : $param_list['page_size'];
        //校验时间标志
        $check_info = $this->checkPeriodParam($period);
        if ($check_info['code'] != '0000') {
            $this->ajaxReturn(array('code' => '0000', 'code_str' => "时间标志错误"));
        }
        $start_time = $check_info['start_time'];
        $end_time = $check_info['end_time'];
        $cash_list = Service::instance()->find('account', 'record')->getAccountList($user_id, $start_time, $end_time, 'cash', $income_type, $summary_type, $page, $page_size);
        $remain_info = Service::instance()->find('account', 'wallet')->getAvailableRemain($user_id, 'cash');
        $cash_list['count'] = $cash_list['count'] ? $cash_list['count'] : 0;
        $cash_list['code'] = '0000';
        $cash_list['v'] = $param_list['v'];//防重复点击
        $cash_list['income_type'] = $income_type;
        $cash_list['page'] = $page;
        $cash_list['remain'] = $remain_info['Cash'];//可用余额
        if ($cash_list['list']) {
            $filter_list = array();//定义初始化过滤列表
            foreach ($cash_list['list'] as $key => $value) {

                $create_timestamp = strtotime($value['create_time']);
                $time_period = substr(date('Y', $create_timestamp), -2) . '-' . date('m-d', $create_timestamp);
                $coin_type = $value['coin_in'] > 0 ? 'in' : 'out';
                $symbol_type = $coin_type == 'in' ? '+' : '-';

                //@TODO 针对佣金后面Java去除代码
                //@TODO 考虑把type写为配置，没有配置不显示
                if ($value['target_type'] == 'Commission') {
                    $value['target_id'] = '';
                }
                if ($value['category'] == 'Draw') {
                    $value['target_type'] = 'Draw';
                }
                $consign_type = '';
                if (!empty($value['target_id'])) {
                    $lotteryServer = Service::instance()->find('lottery', 'lottery');
                    $projectInfo = $lotteryServer->getLotteryInfo($value['target_id']);
                    $consign_type = $projectInfo['consignType'];
                }
                $filter_list[] = array(
                    'item_cn' => $value['summary_cn'],
                    'create_date' => $time_period,
                    'create_time' => date('H:i:s', $create_timestamp),
                    'amount' => $symbol_type . $value["coin_{$coin_type}"],
                    'target_type' => empty($value['target_type']) ? '' : $value['target_type'],
                    'target_id' => empty($value['target_id']) ? '' : $value['target_id'],
                    'consign_type' => $consign_type,
                );

            }
            unset($cash_list['list'], $cash_list['sum_coinin'], $cash_list['sum_coinout']);
            $cash_list['list'] = $filter_list;
        } else {
            $cash_list['list'] = array();
        }
        $str = $this->encrypt($cash_list);
        if (empty($cash_list)) {
            $this->ajaxReturn(array('code' => '-1002', 'code_str' => "余额信息没有获取到", 'info' => ''));
        } else {
            $this->ajaxReturn(array('code' => '0000', 'code_str' => "余额信息显示成功", 'info' => $str));
        }

    }

    /**
     * 现金明细高级查询
     */
    public function cashAdvanced()
    {

        $this->display('Record/cashadvanced');
    }


    /**
     * 现金明细高级查询结果列表
     */
    public function cashAdvancedDetail()
    {

        $user_id = $this->context->userId;
        //$login_url = '/account/login?from='.rawurlencode('/urecord/cash');
        $paraStr = I('request.para');
        $param_list = $this->decrypt($paraStr);
        $period = empty($param_list['period']) ? '-3_months' : $param_list['period'];//时间标志:默认最近三个月 -3_months
        $income_type = $param_list['income_type'];//收支类型
        $summary_type = $param_list['summary_type'];//类型
        $page = ($param_list['page'] >= 0 && isset($param_list['page'])) ? $param_list['page'] : '-1';
        $page_size = empty($param_list['page_size']) ? '-1' : $param_list['page_size'];


        if (empty($user_id)) {

            $data_list = array('code' => '-1001', 'msg' => '当前记录在登录后才可查看');
            return $this->ajaxReturn($data_list);
        }

        //校验时间标志
        $check_info = $this->checkPeriodParam($period);
        if ($check_info['code'] != '0000') {
            return $this->ajaxReturn($check_info);
        }
        $start_time = $check_info['start_time'];
        $end_time = $check_info['end_time'];
        $cash_list = Service::instance()->find('account', 'record')->getAccountList($user_id, $start_time, $end_time, 'cash', $income_type, $summary_type, $page, $page_size);
        $remain_info = Service::instance()->find('account', 'wallet')->getAvailableRemain($user_id, 'cash');

        $cash_list['code'] = '0000';
        $cash_list['v'] = $param_list['v'];//防重复点击
        $cash_list['income_type'] = $income_type;
        $cash_list['page'] = $page;
        $cash_list['remain'] = $remain_info['Cash'];//可用余额
        if ($cash_list['list']) {
            $filter_list = array();//定义初始化过滤列表
            foreach ($cash_list['list'] as $key => $value) {

                $create_timestamp = strtotime($value['create_time']);
                $time_period = substr(date('Y', $create_timestamp), -2) . '-' . date('m-d', $create_timestamp);
                $coin_type = $value['coin_in'] > 0 ? 'in' : 'out';
                $symbol_type = $coin_type == 'in' ? '+' : '-';
                $filter_list[] = array(
                    'item_cn' => $value['summary_cn'],
                    'create_date' => $time_period,
                    'create_time' => date('H:i:s', $create_timestamp),
                    'amount' => $symbol_type . $value["coin_{$coin_type}"],
                    'target_type' => empty($value['target_type']) ? '' : $value['target_type'],
                    'target_id' => empty($value['target_id']) ? '' : $value['target_id'],
                );
            }
            unset($cash_list['list'], $cash_list['sum_coinin'], $cash_list['sum_coinout']);
            $cash_list['list'] = $filter_list;
        } else {
            $cash_list['list'] = array();
        }

        $this->ajaxReturn($cash_list);
    }

    /**
     * 现金明细高级查询
     */
    public function scoreAdvanced()
    {
        //echo "123";die;
        $this->display('Record/scoreadvanced');
    }


    /**
     * 现金明细高级查询结果列表
     */
    public function scoreAdvancedDetail()
    {
        $user_id = $this->context->userId;

        if (empty($user_id)) {

            $this->ajaxReturn(array("code" => '-1001', 'str_cod' => "请先登录"));
        }

        $param_list = I();
        $period = empty($param_list['period']) ? '-3_months' : $param_list['period'];//时间标志:默认最近三个月 -3_months
        $income_type = $param_list['income_type'];//收支类型
        $summary_type = $param_list['summary_type'];//类型
        $page = ($param_list['page'] >= 0 && isset($param_list['page'])) ? $param_list['page'] : '-1';
        $page_size = empty($param_list['page_size']) ? '-1' : $param_list['page_size'];


        if (empty($user_id)) {

            $data_list = array('code' => '-2001', 'msg' => '当前记录在登录后才可查看');
            return $this->ajaxReturn($data_list);
        }

        //校验时间标志
        $check_info = $this->checkPeriodParam($period);
        if ($check_info['code'] != '0000') {
            return $this->ajaxReturn($check_info);
        }
        $start_time = $check_info['start_time'];
        $end_time = $check_info['end_time'];
        $cash_list = Service::instance()->find('account', 'record')->getAccountList($user_id, $start_time, $end_time, 'score', $income_type, $summary_type, $page, $page_size);
        $remain_info = Service::instance()->find('account', 'wallet')->getAvailableRemain($user_id, 'score');

        $cash_list['code'] = '0000';
        $cash_list['v'] = $param_list['v'];//防重复点击
        $cash_list['income_type'] = $income_type;
        $cash_list['page'] = $page;
        $cash_list['remain'] = $remain_info['Cash'];//可用余额
        if ($cash_list['list']) {
            $filter_list = array();//定义初始化过滤列表
            foreach ($cash_list['list'] as $key => $value) {

                $create_timestamp = strtotime($value['create_time']);
                $time_period = substr(date('Y', $create_timestamp), -2) . '-' . date('m-d', $create_timestamp);
                $coin_type = $value['coin_in'] > 0 ? 'in' : 'out';
                $symbol_type = $coin_type == 'in' ? '+' : '-';
                $filter_list[] = array(
                    'item_cn' => $value['summary_cn'],
                    'create_date' => $time_period,
                    'create_time' => date('H:i:s', $create_timestamp),
                    'amount' => $symbol_type . $value["coin_{$coin_type}"],
                    'target_type' => empty($value['target_type']) ? '' : $value['target_type'],
                    'target_id' => empty($value['target_id']) ? '' : $value['target_id'],
                );
            }
            unset($cash_list['list'], $cash_list['sum_coinin'], $cash_list['sum_coinout']);
            $cash_list['list'] = $filter_list;
        } else {
            $cash_list['list'] = array();
        }
        if (empty($cash_list)) {
            $this->ajaxReturn(array("code" => '-1002', 'str_cod' => "没有查询到积分信息", 'info' => ''));
        } else {
            $this->ajaxReturn(array("code" => '0000', 'str_cod' => "获取查询积分信息", 'info' => $cash_list));
        }
    }

    /*彩金明细*/
    public function handsel()
    {

        $user_id = $this->context->userId;
        $login_url = '/account/login?from=' . rawurlencode('/urecord/handsel');

        if (IS_POST) {
            if (empty($user_id)) {

                $data_list = array('code' => '-2001', 'msg' => '当前记录在登录后才可查看');
                return $this->ajaxReturn($data_list);
            }

            $param_list = I();
            $period = empty($param_list['period']) ? '-3_months' : $param_list['period'];//时间标志:默认最近当天 -0_days
            $income_type = $param_list['income_type'];//收支类型
            $summary_type = $param_list['summary_type'];//类型
            $page = $param_list['page'] >= 0 ? $param_list['page'] : '-1';
            $page_size = empty($param_list['page_size']) ? 10 : $param_list['page_size'];

            //校验时间标志
            $check_info = $this->checkPeriodParam($period);
            if ($check_info['code'] != '0000') {
                return $this->ajaxReturn($check_info);
            }
            $start_time = $check_info['start_time'];
            $end_time = $check_info['end_time'];
            $handsel_list = Service::instance()->find('account', 'record')->getAccountList($user_id, $start_time, $end_time, 'handsel', $income_type, $summary_type, $page, $page_size);;
            //dprint($handsel_list);
            $remain_info = Service::instance()->find('account', 'wallet')->getAvailableRemain($user_id, 'handsel');
            $handsel_list['code'] = '0000';
            $handsel_list['income_type'] = $income_type;
            $handsel_list['page'] = $page;
            $handsel_list['remain'] = $remain_info['Handsel'];//可用余额
            if ($handsel_list['list']) {
                $filter_list = array();//定义初始化过滤列表
                foreach ($handsel_list['list'] as $key => $value) {

                    $create_timestamp = strtotime($value['create_time']);
                    $time_period = substr(date('Y', $create_timestamp), -2) . '-' . date('m-d', $create_timestamp);
                    $coin_type = $value['coin_in'] > 0 ? 'in' : 'out';
                    $symbol_type = $coin_type == 'in' ? '+' : '-';
                    $filter_list[] = array(
                        'item_cn' => $value['summary_cn'],
                        'create_date' => $time_period,
                        'create_time' => date('H:i:s', $create_timestamp),
                        'amount' => $symbol_type . $value["coin_{$coin_type}"],
                        'target_type' => empty($value['target_type']) ? '' : $value['target_type'],
                        'target_id' => empty($value['target_id']) ? '' : $value['target_id'],
                    );
                }
                unset($handsel_list['list'], $handsel_list['sum_coinin'], $handsel_list['sum_coinout']);
                $handsel_list['list'] = $filter_list;
            } else {
                $handsel_list['list'] = array();
            }
            return $this->ajaxReturn($handsel_list);
        } else {
            if (!$user_id) {
                redirect($login_url);
            }
            $this->display('Record/handsel');
        }
    }


    /*红包列表*/
    public function bonus()
    {

        $user_id = $this->context->userId;
        //$login_url = '/account/login?from='.rawurlencode('/urecord/bonus');

        if (empty($user_id)) {

            $data_list = ['code' => '-1001', 'code_str' => '当前记录在登录后才可查看'];

            return $this->ajaxReturn($data_list);
        }

        $paraStr = I('request.para');
        $param_list = $this->decrypt($paraStr);

        /*
         * 红包状态
         * [可使用] => yes
         * [待领取] => not
         * [已过期] => expired
         * [已用完] => used
         */
        $bonus_status = empty($param_list['bonus_status']) ? 'yes' : $param_list['bonus_status'];//默认：可使用

        $page = $param_list['page'] >= 0 ? $param_list['page'] : '-1';

        $page_size = empty($param_list['page_size']) ? 10 : $param_list['page_size'];

        //$bonus_list = Service::instance()->find('account', 'wallet')->getMyBonus($user_id, $bonus_status, '', '', '', $page, $page_size);
        $bonus_list = Service::instance()->find('account', 'wallet')->getMyBonusForPage($user_id, $bonus_status, '', '', '', $page, $page_size);

        $result_list = [];
        $result_list['code'] = '0000';
        $result_list['bonus_status'] = $bonus_status;
        $result_list['page'] = $page;

        $remain_info = Service::instance()->find('account', 'wallet')->getAvailableRemain($user_id, 'bonus');
        $result_list['remain'] = $remain_info['Bonus'];//可用余额

        $result_list['list'] = [];
        if ($bonus_list['list']) {

            foreach ($bonus_list['list'] as $key => $value) {

                $result_list['list'][$key] = [
                    'create_date' => date('Y-m-d', strtotime($value['create_time'])),
                    'activity_cn' => $value['bag_actvity_info']['rule_title'],
                    'amount' => $value['bonus_money'],
                    'used_amount' => $value['used_money'],
                    'freeze_amount' => $value['freeze_money'],
                    'remain_amount' => $value['use_money'],
                    'bonus_status' => $value['get_bonus_status'],
                    'target_type' => 'bonus',
                    'target_id' => '',
                    'bag_account_id' => $value['bag_account_id'],
                    'bag_rule_id' => $value['bag_actvity_info']['bag_rule_id']
                ];

                //使用过的红包进入明细页面
                //@TODO 暂时不考虑加入.
                if ($value['use_bonus_time'] != '0000-00-00 00:00:00' && !empty($value['bag_rule_id'])) {

                    //$result_list['list'][$key]['target_id'] = $value['bag_rule_id'];
                }

                // 过期时间
                $expireDate = $value['expire_date'] == '0000-00-00' || $value['expire_date'] == '' ? '永久有效' : $value['expire_date'];

                if ($value['get_bonus_status'] == 'not') {//待领取
                    $result_list['list'][$key]['time_desc'] = '截至领取日：' . date('Y-m-d', strtotime($value['bag_actvity_info']['end_time']));
                } elseif ($value['get_bonus_status'] == 'yes') {//可使用
                    $result_list['list'][$key]['time_desc'] = '有效日期：' . $expireDate;
                } elseif ($value['get_bonus_status'] == 'used') {//已用完

                    $result_list['list'][$key]['time_desc'] = '使用日期：' . date('Y-m-d', strtotime($value['use_bonus_time']));
                } else {//已过期
                    $result_list['list'][$key]['time_desc'] = '有效期：' . $expireDate;
                }
            }
        }
        unset($result_list['code']);
        $str = $this->encrypt($result_list);
        return $this->ajaxReturn(["code" => "0000", "code_str" => "suc", "info" => $str]);
    }


    /*冻结明细*/
    public function freeze()
    {

        $user_id = $this->context->userId;
        //$login_url = '/account/login?from='.rawurlencode('/urecord/freeze');
        if (empty($user_id)) {

            $data_list = array('code' => '-1001', 'msg' => '当前记录在登录后才可查看');
            return $this->ajaxReturn($data_list);
        }

        $param_list = I();
        $page = $param_list['page'] >= 0 ? $param_list['page'] : '-1';
        $page_size = empty($param_list['page_size']) ? '-1' : $param_list['page_size'];

        $freeze_config = Service::instance()->loadConfig('account', 'user', 'getFreezeCfg');
        $freeze_list = Service::instance()->find('account', 'record')->getFreezeList($user_id, $page, $page_size);
        $remain_info = Service::instance()->find('account', 'wallet')->getFreezeRemain($user_id);
        $freeze_list['code'] = '0000';
        $freeze_list['remain'] = $remain_info['Sum'];//汇总余额
        $freeze_list['page'] = $page;
        if ($freeze_list['list']) {

            $coin_type_conf = Service::instance()->loadConfig('account', 'wallet', 'getCoinType');//获取钱包类型配置
            $filter_list = array();//定义初始化过滤列表
            foreach ($freeze_list['list'] as $key => $value) {

                $create_timestamp = strtotime($value['create_time']);
                $time_period = substr(date('Y', $create_timestamp), -2) . '-' . date('m-d', $create_timestamp);
                $coin_type = $freeze_config[$value['freeze_reason']]['IncomeType'];
                $symbol_type = $coin_type == 'in' ? '+' : '-';
                $filter_list[$key] = array(
                    'reason_cn' => $value['freeze_reason_cn'],
                    'create_date' => $time_period,
                    'create_time' => date('H:i:s', $create_timestamp),
                    'amount' => $symbol_type . $value['money'],
                    'target_type' => $value['target_type'],
                    'target_id' => $value['target_id'],
                );

                //重写reason_cn值
                $freeze_reason_cn = '';
                if ($value['freeze_reason'] == 'BuyLottery') {

                    $freeze_reason_cn = $coin_type_conf[ucfirst($value['account_type'])];
                    $filter_list[$key]['reason_cn'] = $freeze_reason_cn . $value['freeze_reason_cn'];
                }
            }
            unset($freeze_list['list'], $freeze_list['sum_amount']);
            $freeze_list['list'] = $filter_list;
        } else {
            $freeze_list['list'] = array();
        }
        if (empty($freeze_list)) {
            $this->ajaxReturn(array('code' => '1002', 'str_cod' => '没有获取到冻结列表信息', 'info' => ''));
        } else {
            $this->ajaxReturn(array('code' => '0000', 'str_cod' => '已获取到冻结列表信息', 'info' => $freeze_list));
        }
    }

    /*充值明细*/
    public function deposit()
    {
        $user_id = $this->context->userId;
        //$login_url = '/account/login?from='.rawurlencode('/urecord/deposit');

        if (empty($user_id)) {

            $data_list = array('code' => '-1001', 'code_str' => '当前记录在登录后才可查看');
            return $this->ajaxReturn($data_list);
        }
        $paraStr = I('request.para');
        $param_list = $this->decrypt($paraStr);
//        $param_list = I();
        //$page=0;
        //$page_size = 20;
        $page = $param_list['page'] >= 0 ? $param_list['page'] : '-1';
        $page_size = empty($param_list['page_size']) ? '-1' : $param_list['page_size'];
        $pay_method = $param_list['pay_method'];//付款方式
        $status = $param_list['status'];//订单状态
        $period = empty($param_list['period']) ? '-3_months' : $param_list['period'];//时间标志:默认最近当天 -0_days

        //校验时间标志
        $check_info = $this->checkPeriodParam($period);
        if ($check_info['code'] != '0000') {
            return $this->ajaxReturn($check_info);
        }
        $start_time = $check_info['start_time'];
        $end_time = $check_info['end_time'];
        $order_list = Service::instance()->find('account', 'record')->getAccountOrderList($user_id, $start_time, $end_time, 'Save,AgentSave', 'Cash', $pay_method, $status, $page, $page_size);
        $save_list = array('code' => '0000', 'pay_method' => $pay_method, 'status' => $status, 'page' => $page);

        if ($order_list['list']) {
            $symbol_type = '+';
            foreach ($order_list['list'] as $key => $value) {
                $create_timestamp = strtotime($value['create_time']);
                $time_period = substr(date('Y', $create_timestamp), -2) . '-' . date('m-d', $create_timestamp);

                /*重写加款状态值*/
                if (in_array($value['status'], array('Not', 'Audited'))) {

                    $value['status_cn'] = '待付款';
                } elseif ($value['status'] == 'Succeed') {

                    $value['status_cn'] = '成功';
                } else {
                    $value['status_cn'] = '失败';
                }
                $filter_list[] = array(
                    'item_cn' => $value['pay_method_cn'],
                    'status_cn' => $value['status_cn'],
                    'status' => $value['status'],
                    'create_date' => $time_period,
                    'create_time' => date('H:i:s', $create_timestamp),
                    'amount' => $symbol_type . $value['amount'],
                    'target_type' => 'order',
                    'target_id' => empty($value['order_id']) ? '' : $value['order_id'],
                );
            }
            $save_list['count'] = $order_list['count'];
            $save_list['list'] = $filter_list;
        } else {
            $save_list = array();
        }
        unset($save_list['code']);
        $str = $this->encrypt($save_list);//加密
        $this->ajaxReturn(array("code" => "0000", "code_str" => "suc", "info" => $str));

    }


    /*提款明细*/
    public function withDraw()
    {

        $user_id = $this->context->userId;
        //$login_url = '/account/login?from='.rawurlencode('/urecord/withDraw');

        if (empty($user_id)) {

            $data_list = array('code' => '-1001', 'code_str' => '当前记录在登录后才可查看');
            return $this->ajaxReturn($data_list);
        }
        $paraStr = I('request.para');
        $param_list = $this->decrypt($paraStr);
        $page = $param_list['page'] >= 0 ? $param_list['page'] : '-1';
        $page_size = empty($param_list['page_size']) ? '-1' : $param_list['page_size'];
        $status = $param_list['status'];//订单状态
        $period = empty($param_list['period']) ? '-3_months' : $param_list['period'];//时间标志:默认最近当天 -0_days

        //校验时间标志
        $check_info = $this->checkPeriodParam($period);
        if ($check_info['code'] != '0000') {
            return $this->ajaxReturn($check_info);
        }
        $start_time = $check_info['start_time'];
        $end_time = $check_info['end_time'];
        $order_list = Service::instance()->find('account', 'record')->getAccountOrderList($user_id, $start_time, $end_time, 'draw', 'cash', $pay_method, $status, $page, $page_size);
        $draw_list = array('code' => '0000', 'status' => $status, 'page' => $page);
        if ($order_list['list']) {
            $symbol_type = '-';
            foreach ($order_list['list'] as $key => $value) {
                $create_timestamp = strtotime($value['create_time']);
                $time_period = substr(date('Y', $create_timestamp), -2) . '-' . date('m-d', $create_timestamp);
                if ($value['pay_method'] == 'batchPayToWechat') {
                    $filter_list[] = array(
                        'item_cn' => '微信提现',
                        'pay_method' => $value['pay_method'],
                        'status' => $value['status'],
                        'status_cn' => $value['status_cn'],
                        'create_date' => $time_period,
                        'create_time' => date('H:i:s', $create_timestamp),
                        'amount' => $symbol_type . $value['amount'],
                        'target_type' => 'order',
                        'target_id' => empty($value['order_id']) ? '' : $value['order_id'],
                    );
                } else {
                    $filter_list[] = array(
                        'item_cn' => '银行卡提现',
                        'pay_method' => $value['pay_method'],
                        'status' => $value['status'],
                        'status_cn' => $value['status_cn'],
                        'create_date' => $time_period,
                        'create_time' => date('H:i:s', $create_timestamp),
                        'amount' => $symbol_type . $value['amount'],
                        'target_type' => 'order',
                        'target_id' => empty($value['order_id']) ? '' : $value['order_id'],
                    );
                }
            }
            $draw_list['count'] = $order_list['count'];
            $draw_list['list'] = $filter_list;
        } else {
            $draw_list = array();
        }
        unset($draw_list['code']);
        $str = $this->encrypt($draw_list);//加密
        $this->ajaxReturn(array("code" => "0000", "code_str" => "suc", "info" => $str));
        //$this->ajaxReturn($draw_list);
    }

    /*取票订单记录*/
    public function getticket()
    {

        $user_id = $this->context->userId;

        $login_url = '/account/login?from=' . rawurlencode('/urecord/getticket');

        $param_list = I('request.');
        // $param_list['status'] = "fail";
        // $param_list['page'] = 1;
        //$param_list['page_size'] = 20;

        $lottery_service = Service::instance()->find('lottery', 'lottery');

        $status = empty($param_list['status']) ? 'all' : $param_list['status'];
        $page = isset($param_list['page']) ? intval($param_list['page']) : '-1';

        $page_size = isset($param_list['page_size']) ? intval($param_list['page_size']) : -1;

        $result_list = $lottery_service->getTicketOrderLists($user_id, $status, $page, $page_size);

        $respond_list = array();//响应返回列表数据
        $respond_list['page'] = $page;
        $respond_list['page_size'] = $page_size;
        $respond_list['status'] = $status;
        if ($result_list['count'] > 0) {
            $lottery_service = Service::instance()->find('lottery', 'lottery');

            foreach ($result_list['list'] as $key => $value) {

                $create_timestamp = strtotime($value['create_time']);
                $time_period = substr(date('Y', $create_timestamp), -2) . '-' . date('m-d', $create_timestamp);

                $lottery_id = $value['lottery_id'];

                $lottery_info = $lottery_service->getLotteryInfo($lottery_id);

                //定义订单详情关键字
                $target_type = $ticket_id = '';

                //当前方案中奖情况
                $prize_status = '';
                if ($lottery_info['prizeStatus'] == 'Not') {//待开奖

                    $prize_status = '待开奖';
                } elseif (in_array($lottery_info['prizeStatus'], array('Open', 'Prize'))) {//已开奖、中奖

                    if ($lottery_info['netPrize'] > 0) {
                        if ($lottery_info['netPrize'] != $lottery_info['rawPrize']) {//大奖
                            $prize_status = '大奖' . $lottery_info['rawPrize'];
                        } else {
                            $prize_status = '中奖' . $lottery_info['netPrize'];
                        }
                    } else {
                        $prize_status = '未中奖';
                    }
                }

                //操作状态
                $optstatus_desc = '';
                if ($value['get_ticket_status'] == 'yes') {
                    $optstatus_desc = '已完成';
                } elseif ($value['get_ticket_status'] == 'fail') {
                    $optstatus_desc = '已过期';
                } else {
                    $optstatus_desc = '取票';
                }

                //计算方案下票状态
                $printedticket_info = $lottery_service->getPrintDataInfoByLotteryID($lottery_id);
                $total_num = $got_num = 0;
                if ($printedticket_info['total_count'] > 0) {
                    $total_num = $printedticket_info['total_count'];
                    $got_num = $printedticket_info['got_count'];
                }

                $respond_list['list'][$key] = array(
                    'ticket_order_id' => $value['get_ticket_order_id'],//取票订单号
                    'lottery_no' => $lottery_info['lotteryNo'] . '期',//期号
                    'lottery_typecn' => $lottery_info['lotteryTypeCn'],//彩种中文
                    'amount' => $lottery_info['totalMoney'],//方案金额
                    'create_date' => $time_period,//创建日期
                    'create_time' => date('H:i:s', $create_timestamp),//创建时间
                    'optstatus' => $value['get_ticket_status'],//取票状态
                    'optstatus_desc' => $optstatus_desc,//状态描述
                    'prize_status' => $prize_status,//中奖状态
                    'total_num' => $total_num,//总票数
                    'got_num' => $got_num,//已取票数
                    'target_type' => 'ticketOrder',
                    'target_id' => $value['get_ticket_order_id'],
                );
            }
            if (empty($user_id)) {
                $this->ajaxReturn(array('code' => '-1001', 'str_cod' => "请先登录", 'info' => ''));
            }
            if (empty($respond_list)) {
                $this->ajaxReturn(array('code' => '-1002', 'str_cod' => "没有获取到取票订单信息", 'info' => ''));
            } else {
                $this->ajaxReturn(array('code' => '0000', 'str_cod' => "获取到取票订单信息", 'info' => $respond_list));
            }

        }
    }


    /*分析处理参数中时间*/
    private function checkPeriodParam($period)
    {


        if (strpos($period, '_') !== false) {
            $period_list = explode('_', $period);
            $int_num = intval($period_list[0]);
            $time_num = strval($period_list[1]);

            if ($int_num <= 0) {
                if ($int_num == 0) {
                    $start_time = date('Y-m-d 00:00:00');
                    $end_time = date('Y-m-d 23:59:59');
                } else {
                    $start_time = date('Y-m-d 00:00:00', strtotime("{$int_num} {$time_num}"));
                    $end_time = date('Y-m-d 23:59:59');
                }
            }
        }
        if ((strtotime($end_time) - strtotime($start_time)) > 86400 * 93) {//校验时间：超过3个月返回错误

            $data_list = array('code' => '-2002', 'code_str' => '时间格式有误');
            return $data_list;
        }
        return array('code' => '0000', 'start_time' => $start_time, 'end_time' => $end_time);
    }


    /**
     * 红包详情页
     * @param string $id bag_account_id
     * @param string $status 红包使用状态
     */
    public function bonusDetail($id)
    {
        $id = I('request.id', '');
        if (!$id) {
            $this->ajaxReturn(array('code' => '-0001', 'str_msg' => '红包id不能为空'));
        }

        $bonus_info = (new wallet())->getBonusByAccountId($id);
        $activity_info = (new bonusEvent())->getEventInfo($bonus_info['bag_actvity_info']['bag_rule_id']);
        $event = array_merge($bonus_info, $activity_info);
        $bonus_detail_info = (new userBonusEvent())->getBonusDetailById($id);
        $return_info = array(
            'bonus_detail' => $bonus_detail_info,
            'is_enable' => $event['is_enable'],
            'activation_time' => $event['activation_time'],
            'use_money' => $event['use_money'],
            'key_code' => $event['key_code'],
            'event' => $event
        );

        $this->ajaxReturn(array(
            'code' => '0000',
            'code_str' => '获取成功',
            'info' => $return_info
        ));

    }


}
